package cn.com.wxd.action.admin.attach;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.wxd.action.AjaxResult;
import cn.com.wxd.service.attach.AttachUtil;
import cn.com.wxd.common.file.MyFileUtil;
import cn.com.wxd.common.thread.ThreadPoolUtil;

/**
 * Title:
 * Description: 文件管理控
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2017
 * All right reserved.
 * Created by WangXuDong on 2017/7/1.
 *
 * @author WangXuDong
 * @version 1.0
 */
@Controller
@RequestMapping("/admin/attach")
public class AttachCtl {

    private static final Logger log = LoggerFactory.getLogger(AttachCtl.class);

    /**
     * 删除附件
     *
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public AjaxResult deleteAttach(String fileName, String paramName, @RequestParam(required = false,
            defaultValue = "false") String isAsynchr) {
        //TODO 在之后会加入从数据库删除相关记录
        try {
            final String fileNameStr = fileName;
            final String attapath = AttachUtil.instance().getAttachConfByParamName(paramName).getPath();
            if (isAsynchr.equalsIgnoreCase("true")) {
                Runnable deleteThread = new Runnable() {
                    @Override
                    public void run() {
                        MyFileUtil.deleteFile(new File(attapath + fileNameStr.substring(0, 8) + "/" + fileNameStr));
                    }
                };
                ThreadPoolUtil.submintThread(deleteThread);
                return AjaxResult.successResult("删除中。。。");
            } else {
                int re = MyFileUtil.deleteFile(new File(attapath + fileName.substring(0, 8) + "/" + fileName));
                if (re == 0) {
                    return AjaxResult.successResult("删除成功");
                } else if (re == -1) {
                    return AjaxResult.failureResult("文件不存在");
                } else {
                    return AjaxResult.errorResult("删除文件出现异常", new Exception("删除文件异常"));
                }
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                return AjaxResult.errorResult("删除文件出现异常", e);
            }
        }
        return AjaxResult.failureResult("删除失败");
    }
}
